from datetime import datetime
from django.core.paginator import Paginator
from django.http import Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from pyplog.artists.models import Artist
from pyplog.photos.models import Gallery, License, Location, Photo, Tag

# maps the key slugs to the respective Model classes
key_classes = {
	"artist" : Artist,
	"gallery" : Gallery,
	"license" : License,
	"location" : Location,
	"tag" : Tag,
}

def photo_detail(request, slug):
	"""
	View for a photo's detail page.
	"""
	photo = get_object_or_404(Photo, slug = slug)
	if photo.published > datetime.now():
		raise Http404
	try:
		next_photo = photo.gallery.photos.filter(published__gt = photo.published).order_by("published")[0]
	except IndexError:
		next_photo = None
	try:
		prev_photo = photo.gallery.photos.filter(published__lt = photo.published).order_by("-published")[0]
	except IndexError:
		prev_photo = None
	
	context_data = {
		"feed_url" : photo.gallery.get_feed_url(),
		"photo" : photo,
		"next_photo" : next_photo,
		"prev_photo" : prev_photo,
	}
	
	return render_to_response(
		"photos/photo_detail.html",
		context_data,
		context_instance = RequestContext(request),
	)

def photo_list(request, key, slug):
	"""
	View to filter photos by a certain key object.
	"""
	key_class = key_classes[key]
	key_object = get_object_or_404(key_class, slug = slug)
	context_data = {
		"feed_url" : key_object.get_feed_url(),
		"key" : key_object,
		"page_title" : key[0].upper() + key[1:] + ": " + key_object.title,
	}
	return render_to_response(
		"photos/photo_list.html",
		context_data,
		context_instance = RequestContext(request),
	)
